package com.etl.dataflow.executor.connectivity.connector;

import com.etl.dataflow.common.entity.JdbcProperties;
import com.etl.dataflow.executor.connectivity.DynamicDatasource;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class OracleConnector implements Connector {

    private static final Map<JdbcProperties, HikariDataSource> DATA_SOURCE_CACHE = new HashMap<>(8);

    @Override
    public Connection getConnection(JdbcProperties jdbcProperties) throws SQLException {
        if (!DATA_SOURCE_CACHE.containsKey(jdbcProperties)) {
            synchronized (DATA_SOURCE_CACHE) {
                if (!DATA_SOURCE_CACHE.containsKey(jdbcProperties)) {
                    String url = "jdbc:oracle:thin:@" + jdbcProperties.getHost() + ":" +
                            jdbcProperties.getPort() + "/" + jdbcProperties.getInstanceName();
                    System.out.println(url);
                    HikariDataSource dataSources = DynamicDatasource.getDataSources(url, jdbcProperties.getUser(), jdbcProperties.getPwd());
                    DATA_SOURCE_CACHE.put(jdbcProperties, dataSources);
                }
            }
        }
        return DATA_SOURCE_CACHE.get(jdbcProperties).getConnection();
    }
}
